﻿
var Page_Preset = (function ()
{
    var _currentStep=0;
    var _totalSteps=10;

    function sleep(milliseconds) {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > milliseconds) {
                break;
            }
        }
    }

    function moveBar() {
        var progessParentW = $('.contentProgress').width();
        var percent = 0;

        percent = (_currentStep / _totalSteps) * progessParentW;
        $('#barCurrentProgress').animate({ width: percent }, 0);
    }

    function updateStatusMessage(type,textToUse) {

        switch (type)
        {
            case 'list':
                //$('#ulTaskslist').append('<li>' + textToUse + '</li>');
                //_currentStep += 1;
                //moveBar();
                break;
            case 'step':
                $('#current_step').text(textToUse);
                break;
            case 'step_details':
                $('#current_step_subtitle').text(textToUse);
                if (textToUse =='Configuration is Complete. Click on Continue to Begin')
                {
                    //show the Done button
                    $("#continueButtonSection").css("display", "inline-block");
               
                }
                break;
        }
    }

   
    function CreateAllTables() {
        dataService.createTable(appGlobalVars.table_UserCred());
        //Determine if local.[tblUContacts] exists; If no, Create table  local.[tblUContacts] exists
        dataService.createTable(appGlobalVars.table_Contacts());
        dataService.createTable(appGlobalVars.table_ContactInfos());
        dataService.createTable(appGlobalVars.table_Reminders());
        dataService.createTable(appGlobalVars.table_ContactCategories());

    }

    function Perform_First_Time_Actions() {
        console.log('Entering Perform_First_Time_Actions');

        statusMessage = 'Performing first time action....';
        updateStatusMessage('step_details', statusMessage);
        updateStatusMessage('list', statusMessage);

        //create all the tables
        CreateAllTables();
  
      

        //TODO:In Pro Version
        //Determine phone is online and server can be reached.

        //TODO:In Pro Version
        //Create entry in server.tblUCred] and return key


        //Store user key in local.[tblUCred]
        dataService.initialize_Table_UCred_withKey(deviceService.deviceKey());

        //Call Functionality [Perform Contact List Sync]
        Perform_ContactList_Synch();
    }

    function Perform_ContactList_Synch() {
        console.log('entering: Perform_ContactList_Synch');

        statusMessage = 'Synching Contact List....';
        updateStatusMessage('step_details', statusMessage);
        updateStatusMessage('list', statusMessage);

 
        //Call Functionality [Read Contacts from Phone]
       // Read_Contacts_FromPhone();

        //for each Contact, Call Functionality [Create/Update Single Contact]
        Synch_Contacts_FromPhone_ToLocalStorage();

        //if pro, Call Functionality [Perform Contact Server Synch]
    }

    function SaveContactsInLocalDB(contacts) {
        
        console.log('entering: SaveContactsInLocalDB');
        //console.log(contacts);

        //TODO:pushing extra contacts to the database [20 times over]
        //for (var j = 0; j < 80; j++) {

        var totalContacts = contacts.length;

            //this is the actual success method that we'll deal with
            for (var i = 0; i < totalContacts; i++) {

               // console.log('saving: ' + (contacts[i].displayName));
                //save the single contact
                SaveSingleContacts_InLocalDB(contacts[i], i + 1, totalContacts);
                //SaveSingleContacts_InLocalDB(contacts[i], i + 1, totalContacts);
                //SaveSingleContacts_InLocalDB(contacts[i], i + 1, totalContacts);
                //SaveSingleContacts_InLocalDB(contacts[i], i + 1, totalContacts);
                //SaveSingleContacts_InLocalDB(contacts[i], i + 1, totalContacts);
            }
        //}

    }

    function SaveSingleContacts_InLocalDB(singleContact, currentCount, totalCount) {
        console.log('entering: SaveSingleContacts_InLocalDB');

        //get the total count first
        dataService.getContacts_Count_FromLocalStorage(
                function save_contactTtotal(totalContactsRecords) {
                    if (localStorage) {
                        localStorage.setItem('totalContacts', totalContactsRecords);
                    }
                }
            );


        dataService.save_SingleContact(singleContact,
                function success_callback_handler(newKey) {

                    console.log('entering save_SingleContact.success.callbackHandler');

                    //save the emails, if any
                    if (singleContact.emails) {
                        console.log('saving email');
                        for (var j = 0; j < singleContact.emails.length; j++) {
                            console.log(singleContact.emails[j]);
                            var contactInfo_emails = new Object();
                            contactInfo_emails.UKey_Contact = newKey;
                            contactInfo_emails.type = singleContact.emails[j].type;
                            contactInfo_emails.value = singleContact.emails[j].value;
                            contactInfo_emails.pref = singleContact.emails[j].pref;
                            contactInfo_emails.group = 'emails';


                            console.log("Type: " + singleContact.emails[j].type + "\n" +
                                    "Value: " + singleContact.emails[j].value + "\n" +
                                    "Preferred: " + singleContact.emails[j].pref);

                            dataService.save_SingleContactInfo(contactInfo_emails);
                        }
                    }

                    //save the phone numbers, if any
                    if (singleContact.phoneNumbers) {
                        console.log('saving phone');
                        for (var j = 0; j < singleContact.phoneNumbers.length; j++) {
                            var contactInfo_phone = new Object();
                            contactInfo_phone.UKey_Contact = newKey;
                            contactInfo_phone.type = singleContact.phoneNumbers[j].type;
                            contactInfo_phone.value = singleContact.phoneNumbers[j].value;
                            contactInfo_phone.pref = singleContact.phoneNumbers[j].pref;
                            contactInfo_phone.group = 'phoneNumbers';


                            console.log("Type: " + singleContact.phoneNumbers[j].type + "\n" +
                                    "Value: " + singleContact.phoneNumbers[j].value + "\n" +
                                    "Preferred: " + singleContact.phoneNumbers[j].pref);

                            dataService.save_SingleContactInfo(contactInfo_phone);
                        }
                    }

                    //save the photos, if any
                    if (singleContact.photos) {
                        console.log('saving photos');
                        var picturePathToUse;
                        for (var j = 0; j < singleContact.photos.length; j++) {
                            var contactInfo_photo = new Object();
                            contactInfo_photo.UKey_Contact = newKey;
                            contactInfo_photo.type = singleContact.photos[j].type;
                            contactInfo_photo.value = singleContact.photos[j].value;
                            contactInfo_photo.pref = singleContact.photos[j].pref;
                            contactInfo_photo.group = 'photos';


                            console.log("Type: " + singleContact.photos[j].type + "\n" +
                                    "Value: " + singleContact.photos[j].value + "\n" +
                                    "Preferred: " + singleContact.photos[j].pref);

                            //use the first photo but if we find the preferred photo, use it instead....
                            if (j == 0 || (singleContact.photos[j].pref)) {
                                picturePathToUse = contactInfo_photo.value;
                            }

                            dataService.save_SingleContactInfo(contactInfo_photo);
                        }

                        //did we get a pref picture? if not we keep the first one as the main picture
                        dataService.update_Table_UContacts_withPicture(newKey, picturePathToUse);
                    }

                    //var totalCount=2000;
                    statusMessage = 'Synching Contact List....';
                    updateStatusMessage('step_details', statusMessage + currentCount + ' out of ' + totalCount + ' Contacts');

                    if (currentCount == totalCount) {
                        statusMessage = 'Configuration is Complete. Click on Continue to Begin';
                        updateStatusMessage('step_details', statusMessage);
                        updateStatusMessage('list', statusMessage);

                        $("#loadingImageSection").css("display", "none");
                        //let's hide the icon and show the continue button


                        //TODO:send to contacts
                       // window.location = "contacts.html";
                    }
                   
                },
                function error_callback_handler(errorMsg) {
                    console.log('entering save_SingleContact.error.callbackHandler');
                    console.log(errorMsg);
                }
            );

               

                
           

               

        

        //dataService.SaveContact_Emails(contactKey,singleContact.id,arrEmails)
        //dataService.SaveContact_PhoneNumbers(contactKey, singleContact.id, arrPhoneNumbers)
    }

    function Synch_Contacts_FromPhone_ToLocalStorage() {

        console.log('entering: Synch_Contacts_FromPhone_ToLocalStorage');

        //get the contacts from the device
        phoneContactService.getContacts_FromDevice(
                function successCallBack(contacts)
                {
                    SaveContactsInLocalDB(contacts);
                },
                function errorCallBack(contactError)
                {
                    console.log('Phase1: Unable to synch contacts with phone ' + contactError);
                }
           )

        console.log('exiting: Synch_Contacts_FromPhone_ToLocalStorage');

    }

    //********************************************************************/
    //Determine Firsttime
    //********************************************************************/
    function DetermineFirstTime( callBack ) {
        console.log('entering DetermineFirstTime');

           
        //start the database
        //dataService.startDatabase();
        //var result = dataService.isTableExists(appGlobalVars.table_UserCred());
        var result = true;

        callBack(result);

        /*if (result)
        {
            console.log('you exists buddy, not your first time');
            return false;
        }
        console.log('first time');

        return true;
        */
        ////do we have the user table
        //returnValue=dataService.isTableExists(appGlobalVars.table_UserCred(),
        //     function (status, err) {
        //         return (!status);
        //         //if (!status) {
        //         //    returnValue= 0;  //table does not exists, so it's first time
        //         //}
        //         //else {
        //         //    returnValue= 1;  //table exists
        //         //}
        //     });

        //alert(returnValue);
        //return returnValue;
    } //end function

    /*Exposed Methods*/
    return {


        //********************************************************************/
        //Determine Firsttime
        //********************************************************************/
        fn_PerformPreset: function (  ) {

            //start the database
            
            dataService.startDatabase();

            alert('deleting data...');
            //drop the local storage key
            localStorage.removeItem('queryOpts')

            alert('deleting data...step 2');

            //drop the tables
            dataService.dropTable(appGlobalVars.table_ContactInfos());
            alert('droping: ' + appGlobalVars.table_ContactInfos())
            dataService.dropTable(appGlobalVars.table_Contacts());
            alert('droping: ' + appGlobalVars.table_Contacts())
            dataService.dropTable(appGlobalVars.table_UserCred());
            alert('droping: ' + appGlobalVars.table_UserCred())


            //this.fn_init();
            alert('initiating data again...');

            //drop the tables
            dataService.dropTable(appGlobalVars.table_ContactInfos());
            dataService.dropTable(appGlobalVars.table_Contacts());
            dataService.dropTable(appGlobalVars.table_UserCred());

            window.location = "presets.html";
        },
        //********************************************************************/
        //Init function
        //********************************************************************/
        fn_init: function () {

            
            var statusMessage;

            statusMessage = 'Verifying Application Data';
            updateStatusMessage('step', statusMessage);
           
          
            /****************************************************/
            //determine build
            /****************************************************/
            statusMessage = 'Determining build....';
            updateStatusMessage('step_details', statusMessage);
            updateStatusMessage('step_details', statusMessage + appGlobalVars.appBuild());
            updateStatusMessage('list', statusMessage + appGlobalVars.appBuild());

            /****************************************************/
            //determine pro or free
            /****************************************************/
            statusMessage = 'Determining Version....';
            updateStatusMessage('step_details', statusMessage);

            var theVersion = "Free";
            if (appGlobalVars.isProVersion())
                theVersion = "Pro";
            updateStatusMessage('step_details', statusMessage + theVersion);
            updateStatusMessage('list', statusMessage + theVersion);
          
            /****************************************************/
            //Getting the device Key
            /****************************************************/
            statusMessage = 'Getting Device Information....';
            updateStatusMessage('step_details', statusMessage);
            var deviceKey =  deviceService.deviceKey();
            var deviceName = deviceService.deviceName();
            var theDeviceInfo = 'Device Key: ' + deviceKey + ' - Device Name: ' + deviceName;
            updateStatusMessage('step_details', statusMessage + theDeviceInfo);
            updateStatusMessage('list', statusMessage + theDeviceInfo);
           

            /****************************************************/
            //determine first time
            /****************************************************/
            statusMessage = 'Determining First Time Use....';
            updateStatusMessage('step_details', statusMessage);

            //alert('here: ' + this.fn_determineFirstTime());

            //appGlobalVars.set_IsFirstTime(this.fn_determineFirstTime());
            //var theFirstime = "Yes";
            //if (!appGlobalVars.isFirstTime())
            //    theFirstime = "No";
            //updateStatusMessage('step_details', statusMessage + theFirstime);
            //updateStatusMessage('list', statusMessage + theFirstime);


            this.fn_determineFirstTime(

                function successCallBack( isFirstTime )
                {

                    console.log('isFirstTime: ' + isFirstTime);

                    appGlobalVars.set_IsFirstTime(isFirstTime);

                    console.log(appGlobalVars.isFirstTime());

                    if (appGlobalVars.isFirstTime() && appGlobalVars.isProVersion()) {
                        //first time and pro, send to registration page
                
                        statusMessage = 'first time and pro';
                        updateStatusMessage('step_details', statusMessage);
                        updateStatusMessage('list', statusMessage);
                        console.log(statusMessage);
                        window.location = "register.html";

                    }
                    else if (appGlobalVars.isFirstTime() && !appGlobalVars.isProVersion())
                    {
                        statusMessage = 'first time and free';
                        updateStatusMessage('step_details', statusMessage);
                        updateStatusMessage('list', statusMessage);
                        console.log(statusMessage);

                        //first time and free, perform first time actions
                        Perform_First_Time_Actions();

                        //send to the Contacts page
                        // window.location = "contacts.html";
                    }
                    else if (!appGlobalVars.isFirstTime()) {
                        statusMessage = 'not first time';
                        updateStatusMessage('step_details', statusMessage);
                        updateStatusMessage('list', statusMessage);

                        console.log(statusMessage);

                        //been there before
                        //Perform_ContactList_Synch();

                        //send to the Contacts page
                        window.location = "contacts.html";
                    }
                }
             )


                      
          


            //setInterval(function () { var x; x = x + 1; }, 2000);

            //percent = .60 * progessParentW;
            //$('#current_step').text('moving forward');
            //$('#barCurrentProgress').animate({ width: percent }, 1000);
            //// alert('really dude!?');

            //setInterval(function () { var x; x = x + 1; }, 2000);
            //percent = progessParentW;
            //$('#current_step').text('moving full speed');
            //$('#barCurrentProgress').animate({ width: percent }, 1000);

            //alert(progessParentW);
        },  //end Init Function

        //********************************************************************/
        //Determine Firsttime
        //********************************************************************/
        fn_determineFirstTime: function ( callBack ) {

           
            //start the database
            dataService.startDatabase();
             
            //TODO:Remove after test
            dataService.dropTable(appGlobalVars.table_UserCred());
            dataService.dropTable(appGlobalVars.table_Contacts());
            dataService.dropTable(appGlobalVars.table_ContactInfos());


            dataService.isTableExists(
                    appGlobalVars.table_UserCred(), 
                    function tableExistsCallBack(foundIt, error) {
                        //return the inverse [if the table is found, then it's not the first time]
                        console.log('foundIt: ' + foundIt);
                        callBack(!foundIt);
                    }

                    );
           

            /*if (result)
            {
                console.log('you exists buddy, not your first time');
                return false;
            }
            console.log('first time');

            return true;
            */
            ////do we have the user table
            //returnValue=dataService.isTableExists(appGlobalVars.table_UserCred(),
            //     function (status, err) {
            //         return (!status);
            //         //if (!status) {
            //         //    returnValue= 0;  //table does not exists, so it's first time
            //         //}
            //         //else {
            //         //    returnValue= 1;  //table exists
            //         //}
            //     });

            //alert(returnValue);
            //return returnValue;
        } //end function
   
    };
    
}());